<?php

namespace app\command;

use app\common\model\SmsChannel;
use app\common\model\SmsTemplate;
use app\common\model\TencentSms;
use app\common\model\TencentSmsLog;
use app\common\model\Tools;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Exception;

class TencentSmsStatus extends Command
{

    protected function configure()
    {
        $this->setName('tencent_sms_status')->setDescription('腾讯短信发送状态查询');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('tencent_sms_status');
        $tx_sms_model = new TencentSms();
        try {
            $log_list = (new TencentSmsLog())->where(['notify_status' => 0, 'createtime' => ['<=', time() - 3600]])->select();
            if ($log_list) {
                foreach ($log_list as $log) {
                    $sms_config = (new SmsTemplate())->fetch(['key' => $log['sms_key']])['data'];
                    if (!$sms_config) {
                        continue;
                    }

                    $sms_channel = (new SmsChannel())->fetch(['id' => $sms_config['sms_channel_id']])['data'];
                    if (!$sms_channel) {
                        continue;
                    }
                    $result = $tx_sms_model->querySendStatus($sms_channel, $log['mobile']);
                    foreach ($result['PullSmsSendStatusSet'] as $record) {
                        if ($record['ReportStatus'] == 'SUCCESS') {
                            (new TencentSmsLog())->edit(['serial_no' => $record['SerialNo']], ['status' => 1, 'message' => '用户短信送达成功', 'notify_status' => 1]);
                        } else {
                            (new TencentSmsLog())->edit(['serial_no' => $record['SerialNo']], ['status' => 0, 'message' => $record['Description'], 'notify_status' => 1]);
                        }
                    }
                }
            }
            echo 'OK';
        } catch (Exception $exception) {
            Tools::log('./tencent_sms_status.log', [$exception->getLine(), $exception->getMessage()]);
        }
    }
}
